package com.qlm.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.PropKit;


/**
 * 二维码通用校验类,会返回一个QrcodeVerify对象 ，可以取到 表的序号，二维码，与 加密标识
 * 建议以后的产码都是A+code+4位标识
 * @author wangzih
 *
 */
public class QrcodeVerify {
	static Logger logger = LoggerFactory.getLogger(QrcodeVerify.class);
	
	@Override
	public String toString() {
		return "QrcodeVerify [isVerify=" + isValid + ", table_num=" + table_num + ", key=" + key + ", qrCode="
				+ qrCode + "]";
	}

	private boolean isValid = false;//有效性
	private String table_num;//表的序号
	private String key;//标识
	private int qrCode;//二维码

	/**
	 *获取表序号+code
	 */
	public String getFullCode(){
		return table_num+qrCode;
	}
	
	public boolean isValid() {
		return isValid;
	}

	public void setVaild(boolean isValid) {
		this.isValid = isValid;
	}

	public String getTable_num() {
		return table_num;
	}

	public void setTable_num(String table_num) {
		this.table_num = table_num;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public int getQrCode() {
		return qrCode;
	}

	public void setQrCode(int qrCode) {
		this.qrCode = qrCode;
	}

	private static String escape(String code) {
		code = code.trim();
		StringBuilder sb = new StringBuilder();
		for (int i = 0, len = code.length(); i < len; i++) {
			char c = code.charAt(i);
			if (c == '$') {
				sb.append("+");
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}
	
	/**
	 * 校验方法，通过返回的对象来获取码的所有信息
	 * @param code
	 * @return
	 */
	public static QrcodeVerify verify(String code) {
		QrcodeVerify qv = new QrcodeVerify();
		DESUtil des = new DESUtil(PropKit.get("decipherKey"));
		try {
			code = escape(code);
			String decryptStr = des.decryptStr(code);
			checkLength(decryptStr);
			String tableNum = checkTableNum(decryptStr);
			qv.setTable_num(tableNum);
			int len = decryptStr.length();
			String qrCodeStr = decryptStr.substring(1,len-4);
			int qrCodeNum = Integer.parseInt(qrCodeStr);
			qv.setQrCode(qrCodeNum);
			String key = decryptStr.substring(len-4);
			qv.setKey(key);
			qv.setVaild(true);
			return qv;
		} catch (Exception e) {
			logger.error("解码失败,二维码为:"+code,e);
			qv.setVaild(false);
			return qv;
		}
	}

	private static  String  checkTableNum(String decryptStr) {
		char num = decryptStr.charAt(0);
		if(num>='A' && num<='Z'){
			return (num+"").toLowerCase();
		}else{
			throw new RuntimeException("码的第一位不是不是大写字母");
		}
		
	}

	private static void checkLength(String decryptStr) {
		int length = decryptStr.length() ;
		if(length <6 || length>14){//如果码长度不对
			throw new RuntimeException("码长度不对");
		}
		
	}

	public static void main(String[] args) {
		DESUtil a = new DESUtil("lanjiaqi");
		String encryptStr = a.encryptStr("A123d232sa1");
		QrcodeVerify verify = QrcodeVerify.verify(encryptStr);
		System.out.println(verify);
	}
}
